package com.example.exp4.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.example.exp4.MyDbHelper;

import static com.example.exp4.MyDbHelper.TB_NAME;

public class PersonDao {
    private MyDbHelper dbHelper;//类的成员
    private SQLiteDatabase myDb;
    //构造方法，参数为上下文对象和数据库名
    public PersonDao(Context context) {
        this.dbHelper = new MyDbHelper(context,"test.db",null,1);
    }
//插入数据
    public void insert(String name, Integer age) {
        myDb = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name",name);
        values.put("age",age);
        long result = myDb.insert(TB_NAME, null, values);
        //这里的result是插入的结果
        if (result == -1) {
            Log.i("crud","数据插入失败！");
        }else {
            Log.i("crud","数据插入成功！行号："+ result);
        }
    }

    public Cursor selectAll() {
        myDb = dbHelper.getReadableDatabase();
        return myDb.rawQuery("select * from person",null);
    }

    public int getCount() {
        Cursor cursor = selectAll();
        return cursor.getCount();
    }

    public void delete(String id) {
        String where = "id=" + id;
        myDb = dbHelper.getWritableDatabase();
        int delete = myDb.delete(TB_NAME, where, null);
        if (delete > 0) {
            Log.i("crud","数据删除成功！");
        }else {
            Log.i("crud","数据删除失败！");
        }
    }

    public void update(String id, String name, int age) {
        myDb = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name",name);
        values.put("age",age);
        String where = "id=" + id;
        int l = myDb.update(TB_NAME, values,where,null);
        if (l > 0) {
            Log.i("crud","数据更新成功！");
        }else {
            Log.i("crud","数据更新失败！");

        }
    }
}
